//
// Created by HQF on 2024/8/9.
//

#include "FFmpeg.h"
#include "commit.h"
#include <media/NdkMediaCodec.h>

static const char *TAG = "FFMPEG";

static AVPacket *pkt;
static AVFrame *frame;
static const AVCodec* codec = nullptr;
static AVCodecContext* ctx = nullptr;

static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt)
{
    int ret;

    /* send the frame to the encoder */
    if (frame)
        LOGI("Send frame %ld", frame->pts);

    ret = avcodec_send_frame(enc_ctx, frame);
    if (ret < 0) {
        LOGI( "Error sending a frame for encoding\n");
        exit(1);
    }

    while (ret >= 0) {
        ret = avcodec_receive_packet(enc_ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            LOGI( "Error during encoding\n");
            exit(1);
        }

        LOGI("Write packet %ld (size=%5d)", pkt->pts, pkt->size);
        // fwrite(pkt->data, 1, pkt->size, outfile);
        av_packet_unref(pkt);
    }
}

bool createEncoder(int width, int height, int fps, int bitrate) {
    LOGD("width %d width %d fps %d bitrate %d", width , height, fps, bitrate);
    int ret = 0;
    // 找到编码器
    codec = avcodec_find_encoder_by_name("libx264");
    if (!codec) {
        LOGD("InitVideoCodec 获取解码器出错");
        return false;
    }
    // 创建编码器上下文
    ctx = avcodec_alloc_context3(codec);
    if (!ctx) {
        LOGD("InitVideoCodec 获取解码器上下文出错");
        return false;
    }
    // 配置编码器参数
    ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    ctx->flags |= AV_CODEC_FLAG_LOW_DELAY;
    ctx->codec_id = codec->id;
    ctx->thread_count = 4;
    //压缩后每秒视频的bit位大小 400 kbps \ 2500kbps
    ctx->bit_rate = bitrate;
    ctx->width = width;
    ctx->height = height;
    ctx->time_base = {1, 1000};
    ctx->framerate = {fps, 1};
    ctx->gop_size = 2 * fps;/* 关键帧间隔 */
    ctx->max_b_frames = 0;
    ctx->pix_fmt = AV_PIX_FMT_YUV420P;
    // 编码器属性配置
    AVDictionary* param = nullptr;
    av_dict_set(&param, "preset", "ultrafast", 0);
    av_dict_set(&param, "profile", "baseline", 0);
    av_dict_set(&param, "crf", "22", 0);
    // 打开编码器上下文
    ret = avcodec_open2(ctx, 0, &param);
    if (ret != 0) {
        LOGD("avcodec_open2出错");
        return false;
    }
    pkt = av_packet_alloc();
    if (!pkt)
        exit(1);
    frame = av_frame_alloc();
    if (!frame) {
        LOGI( "Could not allocate video frame\n");
        exit(1);
    }
    frame->format = ctx->pix_fmt;
    frame->width  = ctx->width;
    frame->height = ctx->height;
    ret = av_frame_get_buffer(frame, 0);
    if (ret < 0) {
        LOGI( "Could not allocate the video frame data\n");
        exit(1);
    }
    LOGD("XMediaEncode InitVideoCodec 完成");
    return true;
}

bool releaseEncoder() {
    /* flush the encoder */
    encode(ctx, NULL, pkt);

    avcodec_free_context(&ctx);
    av_frame_free(&frame);
    av_packet_free(&pkt);
}

bool onOutputBufferAvailable(char *buffer, int length, long pts, int flags) {
    LOGD("length %d pts %ld flags %d", length, pts, flags);
    /**
     * Make sure the frame data is writable.
     * On the first round, the frame is fresh from av_frame_get_buffer()
     * and therefore we know it is writable.
     * But on the next rounds, encode() will have called
     * avcodec_send_frame(), and the codec may have kept a reference to
     * the frame in its internal structures, that makes the frame
     * unwritable.
     * av_frame_make_writable() checks that and allocates a new buffer
     * for the frame only if necessary.
     */
    int ret = av_frame_make_writable(frame);
    if (ret < 0)
        exit(1);

    /**
     * Prepare a dummy image.
     * In real code, this is where you would have your own logic for
     * filling the frame. FFmpeg does not care what you put in the
     * frame.
     */
    uint8_t *buf_y = frame->data[0];
    uint8_t *buf_u = frame->data[1];
    uint8_t *buf_v = frame->data[2];
    int frame_size = ctx->width * ctx->height;
    memcpy(buf_y, buffer, frame_size);
    memcpy(buf_v, buffer + frame_size, frame_size / 4);
    memcpy(buf_u, buffer + frame_size * 5 / 4, frame_size / 4);
    frame->pts = pts;

    encode(ctx, frame, pkt);

    return true;
}

static AVBufferRef *hw_device_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt;
static FILE *output_file = NULL;

static int hw_decoder_init(AVCodecContext *ctx, const enum AVHWDeviceType type)
{
    int err = 0;

    if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type,
                                      NULL, NULL, 0)) < 0) {
        LOGE("Failed to create specified HW device.\n");
        return err;
    }
    ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);

    return err;
}

static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
                                        const enum AVPixelFormat *pix_fmts)
{
    const enum AVPixelFormat *p;

    for (p = pix_fmts; *p != -1; p++) {
        if (*p == hw_pix_fmt)
            return *p;
    }

    LOGE("Failed to get HW surface format.\n");
    return AV_PIX_FMT_NONE;
}

static int decode(AVCodecContext *avctx, AVPacket *packet)
{
    AVFrame *frame = NULL;
    AVFrame *tmp_frame = NULL;
    uint8_t *buffer = NULL;
    int size;
    int ret = 0;

    ret = avcodec_send_packet(avctx, packet);
    if (ret < 0) {
        LOGE("Error during decoding\n");
        return ret;
    }

    while (true) {
        if (!(frame = av_frame_alloc())) {
            LOGE("Can not alloc frame\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }

        ret = avcodec_receive_frame(avctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            av_frame_free(&frame);
            return 0;
        } else if (ret < 0) {
            LOGE("Error while decoding\n");
            goto fail;
        }

        LOGI("Read frame pts %ld (%dx%d)", frame->pts, frame->width, frame->height);
        //encode(avctx, frame, pkt);

        fail:
        av_frame_free(&frame);
        av_freep(&buffer);
        if (ret < 0)
            return ret;
    }
}

static int decode_write(AVCodecContext *avctx, AVPacket *packet)
{
    AVFrame *frame = NULL, *sw_frame = NULL;
    AVFrame *tmp_frame = NULL;
    uint8_t *buffer = NULL;
    int size;
    int ret = 0;

    ret = avcodec_send_packet(avctx, packet);
    if (ret < 0) {
        LOGE("Error during decoding\n");
        return ret;
    }

    while (true) {
        if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
            LOGE("Can not alloc frame\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }

        ret = avcodec_receive_frame(avctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            av_frame_free(&frame);
            av_frame_free(&sw_frame);
            return 0;
        } else if (ret < 0) {
            LOGE("Error while decoding\n");
            goto fail;
        }

        if (frame->format == hw_pix_fmt) {
            /* retrieve data from GPU to CPU */
            if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
                LOGE("Error transferring the data to system memory\n");
                goto fail;
            }
            tmp_frame = sw_frame;
        } else
            tmp_frame = frame;

        size = av_image_get_buffer_size(AVPixelFormat(tmp_frame->format), tmp_frame->width,
                                        tmp_frame->height, 1);
        buffer = static_cast<uint8_t *>(av_malloc(size));
        if (!buffer) {
            LOGE("Can not alloc buffer\n");
            ret = AVERROR(ENOMEM);
            goto fail;
        }
        ret = av_image_copy_to_buffer(buffer, size,
                                      (const uint8_t * const *)tmp_frame->data,
                                      (const int *)tmp_frame->linesize, AVPixelFormat(tmp_frame->format),
                                      tmp_frame->width, tmp_frame->height, 1);
        if (ret < 0) {
            LOGE("Can not copy image to buffer\n");
            goto fail;
        }

        if ((ret = fwrite(buffer, 1, size, output_file)) < 0) {
            LOGE("Failed to dump raw data.\n");
            goto fail;
        }

        fail:
        av_frame_free(&frame);
        av_frame_free(&sw_frame);
        av_freep(&buffer);
        if (ret < 0)
            return ret;
    }
}

bool createDecoder(std::string file)
{
    AVFormatContext *input_ctx = NULL;
    int video_stream, ret;
    AVStream *video = NULL;
    AVCodecContext *decoder_ctx = NULL;
    const AVCodec *decoder = NULL;
    AVPacket *packet = NULL;
    enum AVHWDeviceType type;
    int i;

    type = av_hwdevice_find_type_by_name("mediacodec");
    if (type == AV_HWDEVICE_TYPE_NONE) {
        LOGE("Device type %s is not supported.", "h264_mediacodec");
        LOGE("Available device types:");
        while((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
            LOGE(" %s", av_hwdevice_get_type_name(type));
        LOGE("\n");
        return -1;
    }

    packet = av_packet_alloc();
    if (!packet) {
        LOGE("Failed to allocate AVPacket\n");
        return -1;
    }

    /* open the input file */
    if (avformat_open_input(&input_ctx, file.c_str(), NULL, NULL) != 0) {
        LOGE("Cannot open input file '%s'", file.c_str());
        return -1;
    }

    if (avformat_find_stream_info(input_ctx, NULL) < 0) {
        LOGE("Cannot find input stream information.\n");
        return -1;
    }

    /* find the video stream information */
    ret = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0);
    if (ret < 0) {
        LOGE("Cannot find a video stream in the input file\n");
        return -1;
    }
    video_stream = ret;

    for (i = 0;; i++) {
        const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
        if (!config) {
            LOGE("Decoder %s does not support device type %s.",
                    decoder->name, av_hwdevice_get_type_name(type));
            decoder = avcodec_find_decoder_by_name("h264_mediacodec");
            break;
        }
        if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
            config->device_type == type) {
            hw_pix_fmt = config->pix_fmt;
            break;
        }
    }

    if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
        return AVERROR(ENOMEM);

    video = input_ctx->streams[video_stream];
    if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0)
        return -1;

    decoder_ctx->get_format  = get_hw_format;

    if (hw_decoder_init(decoder_ctx, type) < 0)
        return -1;

    if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0) {
        LOGE("Failed to open codec for stream #%u", video_stream);
        return -1;
    }

    createEncoder(2160, 3840, 25, 20*1000*1000);

    /* actual decoding and dump the raw data */
    while (ret >= 0) {
        if ((ret = av_read_frame(input_ctx, packet)) < 0)
            break;

        if (video_stream == packet->stream_index)
            ret = decode(decoder_ctx, packet);

        av_packet_unref(packet);
    }

    /* flush the decoder */
    ret = decode(decoder_ctx, NULL);

    av_packet_free(&packet);
    avcodec_free_context(&decoder_ctx);
    avformat_close_input(&input_ctx);
    av_buffer_unref(&hw_device_ctx);

    return 0;
}
